package top.codedance.iotp.tools.serverTool.ui;

import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.iot.sdk.StandandService;
import top.codedance.iotp.iot.sdk.entity.DeviceEntity;
import top.codedance.iotp.iot.sdk.po.sync.AddDeviceParam;
import top.codedance.iotp.tools.serverTool.ServerToolApplication;
import top.codedance.iotp.tools.serverTool.subframe.AddDeviceSubFrame;
import top.codedance.iotp.tools.terminal.TerminalApplication;
import top.codedance.iotp.tools.terminal.ui.WaitLoading;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Lenovo
 */
public class AddDeviceFrame extends javax.swing.JDialog {
    private WaitLoading waitLoading = new WaitLoading(this);
    private MainFrame mf;
    private StandandService standandService;
    private AddDeviceParam addDeviceParam;
    private List<DeviceEntity> devices;
    private DefaultTableModel dtm;

    /**
     * Creates new form AddDeviceFrame
     */
    public AddDeviceFrame(MainFrame mf) {
        super(mf, true);
        this.mf = mf;
        initComponents();
        URL url = Thread.currentThread().getContextClassLoader().getResource("logo.gif");
        ImageIcon icon = new ImageIcon(url);
        setIconImage(icon.getImage());
        setMinimumSize(new Dimension(1062, 643));
        setLocationRelativeTo(this.mf.getShellFrame());
        setTitle("代码飞舞采控系统-添加设备到服务端");
        this.standandService = new StandandService(ServerToolApplication.serverConf.getServerHost());
        addDeviceParam = new AddDeviceParam();
        addDeviceParam.setUsername(ServerToolApplication.serverConf.getUsername());
        addDeviceParam.setPassword(ServerToolApplication.serverConf.getPassword());
        this.devices = new ArrayList<>();

        initTable();
    }

    public MainFrame getMainFrame() {
        return mf;
    }

    public void setModifyMode(JSONObject jo) {
        dtm.addRow(new Object[]{jo.getString("id"), jo.getString("deviceId"), jo.getString("unitName"), jo.getString("registeTime")});
    }

    private void initTable() {
        String[] columnNames = {"id", "deviceId", "unitName", "registeTime"};
        String[][] tdata = new String[0][0];
        dtm = new DefaultTableModel(tdata, columnNames);
        device_jt.setModel(dtm);
    }

    public void addAction(DeviceEntity deviceEntity) {
        devices.add(deviceEntity);
        dtm.addRow(new Object[]{null, deviceEntity.getDeviceId(), deviceEntity.getUnitName(), new Date()});
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jb_add = new javax.swing.JButton();
        jb_save = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        reponseTp = new javax.swing.JTextPane();
        jb_clean = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        device_jt = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jb_add.setLabel("添加设备");
        jb_add.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_addActionPerformed(evt);
            }
        });

        jb_save.setBackground(new java.awt.Color(255, 51, 51));
        jb_save.setForeground(new java.awt.Color(255, 255, 255));
        jb_save.setText("提交");
        jb_save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_saveActionPerformed(evt);
            }
        });

        jLabel1.setText("请求体:");

        jLabel2.setText("响应体:");

        jScrollPane2.setViewportView(reponseTp);

        jb_clean.setLabel("清除设备");
        jb_clean.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_cleanActionPerformed(evt);
            }
        });

        device_jt.setModel(new javax.swing.table.DefaultTableModel(
                new Object[][]{
                        {},
                        {},
                        {},
                        {}
                },
                new String[]{

                }
        ));
        device_jt.setToolTipText("");
        device_jt.setRowHeight(30);
        jScrollPane3.setViewportView(device_jt);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup()
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                        .addGroup(layout.createSequentialGroup()
                                                                .addComponent(jb_add)
                                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                .addComponent(jb_clean))
                                                        .addComponent(jLabel1)
                                                        .addComponent(jLabel2)
                                                        .addComponent(jb_save))
                                                .addGap(0, 425, Short.MAX_VALUE))
                                        .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 563, Short.MAX_VALUE))
                                .addContainerGap())
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jb_add)
                                        .addComponent(jb_clean))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel2)
                                .addGap(8, 8, 8)
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 156, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jb_save)
                                .addGap(12, 12, 12))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jb_saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_saveActionPerformed
        waitLoading.open();
        TerminalApplication.pool.submit(() -> {
            try {
                ArrayList<DeviceEntity> devices = new ArrayList<>();
                for (int i = 0; i < dtm.getRowCount(); i++) {
                    String deviceId = (String) dtm.getValueAt(i, 1);
                    String unitName = (String) dtm.getValueAt(i, 2);
                    DeviceEntity de = new DeviceEntity();
                    de.setDeviceId(deviceId);
                    de.setUnitName(unitName);
                    devices.add(de);
                }
                addDeviceParam.setDevices(devices);
                JSONObject jsonObject = standandService.addDevices(addDeviceParam);
                reponseTp.setText(jsonObject.toJSONString());
                Integer status = jsonObject.getInteger("status");
                if (status == 200) {
                    JOptionPane.showMessageDialog(rootPane, "添加成功");
                } else {
                    JOptionPane.showMessageDialog(rootPane, "请求失败：" + jsonObject.getString("message"));
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(rootPane, "请求失败");
            } finally {
                waitLoading.close();
            }
        });
    }//GEN-LAST:event_jb_saveActionPerformed

    private void jb_addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_addActionPerformed
        new AddDeviceSubFrame(AddDeviceFrame.this).setVisible(true);
    }//GEN-LAST:event_jb_addActionPerformed

    private void jb_cleanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_cleanActionPerformed
        devices.clear();
        initTable();
        reponseTp.setText("");
    }//GEN-LAST:event_jb_cleanActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable device_jt;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JButton jb_add;
    private javax.swing.JButton jb_clean;
    private javax.swing.JButton jb_save;
    private javax.swing.JTextPane reponseTp;
    // End of variables declaration//GEN-END:variables

}
